package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Chat
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.utils.navigateCommentDetail
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import com.sddnytsh.body_buildingsystem.utils.DateUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Composable
fun CommentWithRepliesItem(
    comment: Comment,
    navController: NavController,
    coroutineScope: CoroutineScope,
    communityApiService: CommunityApiService,
    post: CommunityPost?,
    onCommentLikeUpdate: (Long, Boolean, Int) -> Unit,
    onCommentsRefresh: () -> Unit
) {
    var replies by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoadingReplies by remember { mutableStateOf(false) }
    var showReplyInput by remember { mutableStateOf(false) }
    var replyText by remember { mutableStateOf("") }
    var isSubmittingReply by remember { mutableStateOf(false) }
    var replyToUser by remember { mutableStateOf<String?>(null) }

    // 加载该评论的回复
    LaunchedEffect(comment.id) {
        // 避免重复加载 - 只检查是否已经在加载中
        if (isLoadingReplies) {
            return@LaunchedEffect
        }
        
        isLoadingReplies = true
        try {
            val result = communityApiService.getReplies(comment.id, 1, 2) // 只获取前2条
            result.onSuccess { data ->
                val replyList = data["replies"] as? List<Map<String, Any>> ?: emptyList()
                replies = replyList.map { replyData ->
                    Comment(
                        id = (replyData["id"] as? Number)?.toLong() ?: 0L,
                        postId = (replyData["postId"] as? Number)?.toLong() ?: 0L,
                        userId = (replyData["userId"] as? Number)?.toLong() ?: 0L,
                        content = replyData["content"] as? String ?: "",
                        likeCount = (replyData["likeCount"] as? Number)?.toInt() ?: 0,
                        isLiked = replyData["isLiked"] as? Boolean ?: false,
                        createdAt = replyData["createdAt"] as? String ?: "",
                        author = replyData["author"] as? String,
                        parentId = (replyData["parentId"] as? Number)?.toLong(),
                        rootId = (replyData["rootId"] as? Number)?.toLong(),
                        isDeleted = replyData["isDeleted"] as? Boolean ?: false
                    )
                }
            }
        } catch (e: Exception) {
            // 处理错误
        } finally {
            isLoadingReplies = false
        }
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(horizontal = 16.dp, vertical = 8.dp)
    ) {
        // 主评论
        CommentItemWithCallback(
            comment = comment,
            onCommentLikeUpdate = onCommentLikeUpdate,
            onReplyClick = { 
                showReplyInput = !showReplyInput
                replyToUser = comment.author ?: "用户${comment.userId}"
                replyText = "@${replyToUser} "
            }
        )

        // 回复预览区域
        if (replies.isNotEmpty() || isLoadingReplies) {
            Spacer(modifier = Modifier.height(8.dp))
            
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        Color(0xFFF8F9FA),
                        RoundedCornerShape(8.dp)
                    )
                    .padding(12.dp)
            ) {
                Column {
                    // 回复标题和查看更多
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "回复 (${replies.size})",
                            style = MaterialTheme.typography.bodyMedium.copy(
                                fontWeight = FontWeight.Medium,
                                color = Color(0xFF666666)
                            )
                        )
                        
                        Text(
                            text = "查看更多",
                            modifier = Modifier.clickable {
                                navController.navigateCommentDetail(comment.id)
                            },
                            style = MaterialTheme.typography.bodySmall.copy(
                                color = Color(0xFF4361EE),
                                fontWeight = FontWeight.Medium
                            )
                        )
                    }

                    Spacer(modifier = Modifier.height(8.dp))

                    // 显示回复列表
                    if (isLoadingReplies) {
                        Box(
                            modifier = Modifier.fillMaxWidth(),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(20.dp),
                                strokeWidth = 2.dp
                            )
                        }
                    } else {
                        replies.forEach { reply ->
                            ReplyPreviewItem(
                                reply = reply,
                                onReplyLikeUpdate = { replyId: Long, isLiked: Boolean, likeCount: Int ->
                                    // 更新回复的点赞状态
                                    replies = replies.map { r ->
                                        if (r.id == replyId) {
                                            r.copy(isLiked = isLiked, likeCount = likeCount)
                                        } else {
                                            r
                                        }
                                    }
                                },
                                onReplyClick = { replyToReply ->
                                    // 回复二级评论
                                    showReplyInput = true
                                    replyToUser = replyToReply.author ?: "用户${replyToReply.userId}"
                                    replyText = "@${replyToUser} "
                                }
                            )
                            if (reply != replies.last()) {
                                Spacer(modifier = Modifier.height(4.dp))
                            }
                        }
                    }
                }
            }
        }

        // 回复输入框
        if (showReplyInput) {
            Spacer(modifier = Modifier.height(8.dp))
            ReplyInputPreviewSection(
                replyText = replyText,
                onReplyChange = { replyText = it },
                isSubmitting = isSubmittingReply,
                onSendReply = {
                    // 防止重复提交
                    if (isSubmittingReply) {
                        return@ReplyInputPreviewSection
                    }
                    
                    if (replyText.trim().isNotEmpty() && post != null) {
                        coroutineScope.launch {
                            isSubmittingReply = true
                            try {
                                val currentUserId = UserState.currentUserId
                                if (currentUserId != null) {
                                    val result = communityApiService.createReply(
                                        postId = post.id,
                                        parentId = comment.id,
                                        rootId = comment.id,
                                        content = replyText.trim()
                                    )
                                    result.onSuccess { newReply ->
                                        replyText = ""
                                        showReplyInput = false
                                        
                                        // 立即将新回复添加到列表中
                                        val newReplyComment = Comment(
                                            id = newReply.id,
                                            postId = newReply.postId,
                                            userId = newReply.userId,
                                            content = newReply.content,
                                            likeCount = newReply.likeCount,
                                            isLiked = newReply.isLiked,
                                            createdAt = newReply.createdAt,
                                            author = newReply.author,
                                            parentId = newReply.parentId,
                                            rootId = newReply.rootId,
                                            isDeleted = newReply.isDeleted
                                        )
                                        
                                        // 将新回复添加到列表开头
                                        replies = listOf(newReplyComment) + replies
                                        
                                        // 不要刷新一级评论列表，因为回复只显示在预览区域
                                        // onCommentsRefresh() // 注释掉，避免重复显示
                                    }
                                }
                            } catch (e: Exception) {
                                // 处理错误
                            } finally {
                                isSubmittingReply = false
                            }
                        }
                    }
                },
                onCancel = {
                    showReplyInput = false
                    replyText = ""
                }
            )
        }
    }
}

@Composable
fun ReplyPreviewItem(
    reply: Comment,
    onReplyLikeUpdate: (Long, Boolean, Int) -> Unit,
    onReplyClick: (Comment) -> Unit = {}
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.Top
    ) {
        // 用户头像
        if (reply.authorAvatar != null) {
            SimpleAvatarImage(
                avatarUrl = reply.authorAvatar,
                fallbackName = reply.author ?: "用户",
                size = 24.dp
            )
        } else {
            DefaultAvatar(
                name = reply.author ?: "用户",
                size = 24.dp
            )
        }

        Spacer(modifier = Modifier.width(8.dp))

        // 回复内容
        Column(
            modifier = Modifier.weight(1f)
        ) {
            // 用户名和时间
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = reply.author ?: "用户${reply.userId}",
                    style = MaterialTheme.typography.bodySmall.copy(
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF333333)
                    )
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Text(
                    text = DateUtils.formatDate(reply.createdAt),
                    style = MaterialTheme.typography.bodySmall.copy(
                        color = Color(0xFF999999)
                    )
                )
            }

            Spacer(modifier = Modifier.height(2.dp))

            // 回复内容
            Text(
                text = reply.content,
                style = MaterialTheme.typography.bodySmall.copy(
                    color = Color(0xFF333333)
                ),
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )

            Spacer(modifier = Modifier.height(4.dp))

            // 点赞和回复按钮
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // 点赞按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(
                        onClick = {
                            onReplyLikeUpdate(reply.id, !reply.isLiked, reply.likeCount)
                        },
                        modifier = Modifier.size(20.dp)
                    ) {
                        Icon(
                            imageVector = if (reply.isLiked) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
                            contentDescription = "点赞",
                            tint = if (reply.isLiked) Color(0xFFE91E63) else Color(0xFF999999),
                            modifier = Modifier.size(16.dp)
                        )
                    }
                    
                    Text(
                        text = reply.likeCount.toString(),
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = Color(0xFF999999)
                        )
                    )
                }
                
                // 回复按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable {
                        onReplyClick(reply)
                    }
                ) {
                    Icon(
                        imageVector = Icons.Filled.Chat,
                        contentDescription = "回复",
                        tint = Color(0xFF4361EE),
                        modifier = Modifier.size(16.dp)
                    )
                    Spacer(modifier = Modifier.width(2.dp))
                    Text(
                        text = "回复",
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = Color(0xFF4361EE)
                        )
                    )
                }
            }
        }
    }
}

@Composable
fun ReplyInputPreviewSection(
    replyText: String,
    onReplyChange: (String) -> Unit,
    isSubmitting: Boolean,
    onSendReply: () -> Unit,
    onCancel: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                Color(0xFFF8F9FA),
                RoundedCornerShape(8.dp)
            )
            .padding(12.dp)
    ) {
        // 输入框
        OutlinedTextField(
            value = replyText,
            onValueChange = onReplyChange,
            placeholder = { Text("回复...") },
            modifier = Modifier.fillMaxWidth(),
            maxLines = 3,
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = Color(0xFF4361EE),
                unfocusedBorderColor = Color(0xFFE0E0E0)
            )
        )

        Spacer(modifier = Modifier.height(8.dp))

        // 按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.End
        ) {
            TextButton(onClick = onCancel) {
                Text("取消", color = Color(0xFF666666))
            }
            
            Spacer(modifier = Modifier.width(8.dp))
            
            Button(
                onClick = onSendReply,
                enabled = replyText.trim().isNotEmpty() && !isSubmitting,
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF4361EE)
                )
            ) {
                if (isSubmitting) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = Color.White
                    )
                } else {
                    Text("发送", color = Color.White)
                }
            }
        }
    }
}
